<script setup>
import dayjs from 'dayjs'
import {
  ArrowDown,
  CircleCheck,
  Warning,
  CircleClose,
  SemiSelect
} from '@element-plus/icons-vue'
import FormItemSearch from '@/components/form/FormItemSearch.vue'
import TableColumnIndex from '@/components/table/TableColumnIndex.vue'
import { usePagination, useRequest } from '@/hooks'
import { userListApi } from '@/api'
import { validateAndShowTip } from '@/utils'

const ACCOUNT_STATUS = ['待审核', '审核通过', '审核驳回', '冻结']
const ACCOUNT_STATUS_COLOR = [
  'text-info',
  'text-success',
  'text-danger',
  'text-warning'
]
const REAL_NAME_AUTH_STATUS = ['认证未通过', '认证通过']
const REAL_NAME_AUTH_STATUS_COLOR = ['text-danger', 'text-success']

const title = computed(() => useRoute().meta.title ?? '用户列表')

const form = ref({
  userName: '',
  userPhone: '',
  ifCheck: '',
  status: ''
})
const formRef = ref()
function reset() {
  formRef.value.resetFields()
  search()
}

const { pageSize, currentPage, pageSizes } = usePagination({
  onChange: () => refresh()
})

const { refresh, data, count } = useRequest(userListApi.pageAnchorLogin, {
  initialData: [],
  immediate: true,
  params: () => ({
    ...form.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value
  })
})

function search() {
  currentPage.value = 1
  refresh()
}

const selected = ref([])
const selectedIds = computed(() => selected.value.map(item => item.id))
function handleSelectionChange(val) {
  selected.value = val
}

async function handleCommand(command) {
  if (!selectedIds.value.length) return ElMessage.warning('请选择用户')
  const hanlder = {
    pending: () => userListApi.auditStatus({ ids: selectedIds.value }),
    pass: () => userListApi.approvedStatus({ ids: selectedIds.value }),
    reject: () => userListApi.reviewStatus({ ids: selectedIds.value }),
    freeze: () => userListApi.freezeStatus({ ids: selectedIds.value })
  }

  hanlder[command]?.().then(({ code }) => {
    if (code === 200) {
      ElMessage.success('操作成功')
      refresh()
    }
  })
}

const { execute: remove } = useRequest(userListApi.deleteStatus, {
  params: () => ({ ids: selectedIds.value }),
  onSuccess: () => {
    ElMessage.success('删除成功')
    refresh()
  }
})
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header> {{ title }} </template>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
        label-suffix="："
        label-position="left"
        @submit.prevent="search"
      >
        <el-row :gutter="20">
          <FormItemSearch label="用户名" prop="userName">
            <el-input v-model.trim="form.userName" clearable />
          </FormItemSearch>
          <FormItemSearch label="手机号" prop="userPhone">
            <el-input v-model.trim="form.userPhone" clearable />
          </FormItemSearch>
          <FormItemSearch label="是否实名" prop="ifCheck">
            <el-select v-model="form.ifCheck" filterable clearable>
              <el-option
                v-for="(item, index) in REAL_NAME_AUTH_STATUS"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </FormItemSearch>
          <FormItemSearch label="账号状态" prop="status">
            <el-select v-model="form.status" filterable clearable>
              <el-option
                v-for="(item, index) in ACCOUNT_STATUS"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </FormItemSearch>
        </el-row>

        <el-button type="primary" native-type="submit" @submit="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>

        <el-dropdown class="ml-3" trigger="click" @command="handleCommand">
          <el-button>
            审核 <el-icon class="ml-1"> <ArrowDown /> </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="pending" :icon="SemiSelect">
                待审
              </el-dropdown-item>
              <el-dropdown-item command="pass" :icon="CircleCheck">
                通过
              </el-dropdown-item>
              <el-dropdown-item command="reject" :icon="CircleClose">
                驳回
              </el-dropdown-item>
              <el-dropdown-item command="freeze" :icon="Warning">
                冻结
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-button
          type="danger"
          class="ml-3"
          @click="
            validateAndShowTip(remove, selectedIds, { tips: '请选择用户' })
          "
        >
          删除
        </el-button>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <el-table
        :data="data"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <TableColumnIndex :page="currentPage" :page-size="pageSize" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="company" label="机构名称" />
        <el-table-column prop="position" label="职位" />
        <el-table-column prop="userPhone" label="手机号" />
        <el-table-column prop="ifCheck" label="是否实名">
          <template #default="{ row }">
            <span :class="REAL_NAME_AUTH_STATUS_COLOR[row.ifCheck]">
              {{ REAL_NAME_AUTH_STATUS[row.ifCheck] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="账号状态">
          <template #default="{ row }">
            <span :class="ACCOUNT_STATUS_COLOR[row.status]">
              {{ ACCOUNT_STATUS[row.status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createtime"
          label="注册时间"
          :formatter="
            row =>
              row.createtime &&
              dayjs(row.createtime).format('YYYY-MM-DD HH:mm:ss')
          "
        />
        <el-table-column prop="createIp" label="注册IP" />
        <el-table-column
          prop="loginTime"
          label="最近登陆时间"
          :formatter="
            row =>
              row.loginTime &&
              dayjs(row.loginTime).format('YYYY-MM-DD HH:mm:ss')
          "
        />
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="ElMessage('待开发')">
              充值
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="mt-4 justify-end"
        small
      />
    </el-card>
  </div>
</template>
